package com.csx.unionFind;

/**
 * @author 陈胤训
 * @date 2019/6/12 14:13
 * Utils: Intellij Idea
 * Description: 路径压缩 加权的并查集
 */
public class CompressedPathQuickUnion implements UF{

    private int[] parent;

    private int[] sz;

    public CompressedPathQuickUnion(int size) {
        this.parent = new int[size];
        this.sz = new int[size];
        for (int i = 0; i < parent.length; i++) {
            parent[i] = i;
            sz[i] = 1;
        }
    }

    @Override
    public boolean isConnected(int p, int q) {
        return find(p) == find(q);
    }

    @Override
    public void unionElements(int p, int q) {
        int pId = find(p);
        int qId = find(q);
        if (pId == qId){
            return;
        }

        if(sz[pId] < sz[qId]) {
            parent[pId] = qId;
            sz[qId] += sz[pId];
        }else  {
            parent[qId] = pId;
            sz[pId] += sz[qId];
        }

    }

    @Override
    public int getSize() {
        return parent.length;
    }

    /**
     * 查找元素p所对饮的集合编号
     * @param p 元素
     * @return 编号
     */
    private int find(int p){

        if (p < 0 || p >= parent.length){
            throw new IllegalArgumentException("p is out of bound.");
        }

        while(p != parent[p]){
            // 路径压缩 把当前编号更改成上级的上级
            parent[p] = parent[parent[p]];
           p = parent[p];
        }
        return p;
    }

}
